package com.dao.c.backend.interceptor;

import com.dao.c.backend.common.StatusCode;
import com.dao.c.backend.utils.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("Intercepting request for URI: {}", request.getRequestURI());
        if (request.getRequestURI().startsWith("/image/")) {
            log.info("Explicitly allowing /image/ path");
            return true;
        }
        Map<String, Object> map = new HashMap<>();
        // CommonResult result = new CommonResult<>();
        // 令牌建议是放在请求头中，获取请求头中令牌
        String token = request.getHeader("Authorization");
        // 新增：判空与 Bearer 前缀处理，避免 verify 时因 null 触发 NPE
        if (token == null || token.trim().isEmpty()) {
            map.put("message", "未携带令牌");
            map.put("state", StatusCode.NOT_LOGIN);
            String json = JSONObject.toJSONString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            return false;
        }
        if (token.toLowerCase().startsWith("bearer ")) {
            token = token.substring(7).trim();
        }
        try {
            JWTUtil.verify(token);// 验证令牌
            return true;// 放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("message", "无效签名");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("message", "token过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("message", "token算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "token失效");
        }
        map.put("state", StatusCode.NOT_LOGIN);// 设置状态

        String json = JSONObject.toJSONString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
